package com.zw.blog.web.admin;

import com.zw.blog.po.User;
import com.zw.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin") //全局映射
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping //默认使用全局映射
    public String loginPage() {
        return "admin/login"; //return是页面位置，mapping是搜索框输入
    }

    @PostMapping("/login") //会在全局映射后面加入
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {

        User user = userService.checkUser(username, password);
        if (user != null) {
            user.setPassword(null); //不把密码交到页面上
            session.setAttribute("user", user);
            return "admin/index";
        } else {
            //return "admin/login"; //不能直接返回 ??? 会出问题
            //只能用RedirectAttributes，Model作用域不对？？
            attributes.addFlashAttribute("message", "用户名密码错误！");
            return "redirect:/admin";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
